const Koa = require('koa')
const app = new Koa()
const router = require('koa-router')()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const koajwt = require('koa-jwt')
const log4js = require('./utils/log4')
const users = require('./routes/users')
const projects = require('./routes/projects')
const menus = require('./routes/menus')
const plans = require('./routes/plans')
const utils = require('./utils/utils')

// error handler
onerror(app)
// 链接数据库
require('./config/db')
// middlewares
app.use(
  bodyparser({
    enableTypes: ['json', 'form', 'text']
  })
)

app.use(json())
app.use(require('koa-static')(__dirname + '/public'))
app.use(
  views(__dirname + '/views', {
    extension: 'pug'
  })
)

// logger
app.use(async (ctx, next) => {
  if (ctx.request.method === 'POST') {
    log4js.info(`post params:${JSON.stringify(ctx.request.body)}`)
  } else if (ctx.request.method === 'GET') {
    log4js.info(`get params:${JSON.stringify(ctx.request.query)}`)
  }
  // 请求如果401则校验不通过
  await next().catch((err) => {
    if (err.status === 401) {
      // 请求成功，但业务失败
      ctx.status = 200
      ctx.body = utils.fail('Token认识失败', utils.CODE.AUTH_ERROR)
    } else {
      throw err
    }
  })
})

// 校验token有效性
app.use(
  koajwt({ secret: 'teamManager' }).unless({ path: [/^\/api\/user\/login/] })
)
// 公共接口前缀
router.prefix('/api')
// user模块
router.use(users.routes(), users.allowedMethods())
// project模块
router.use(projects.routes(), projects.allowedMethods())
// menus 模块
router.use(menus.routes(), menus.allowedMethods())
// plans 模块
router.use(plans.routes(), plans.allowedMethods())
// routes
app.use(router.routes(), router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  log4js.error(err.stack)
})

module.exports = app
